package com.erp.erp_project.controller;

import com.erp.erp_project.core.annotation.Permission;
import com.erp.erp_project.core.base.AjaxResult;
import com.erp.erp_project.core.exception.CustomException;
import com.erp.erp_project.model.Power;
import com.erp.erp_project.model.User;
import com.erp.erp_project.service.PowerService;
import com.erp.erp_project.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yh
 */
@Controller
@AllArgsConstructor
public class LoginController {
    private UserService userService;
    private PowerService powerService;

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult<User> login1(String username, String password, HttpSession session) throws CustomException {
        User user = userService.login(username, password);
        session.setAttribute("user", user);
        String strs=powerService.query(user.getRole().getRoleId());
        List<String> list=new ArrayList<>();
        //角色的权限
        if(strs!=null&&!strs.trim().equals("")){
            List<Power> powers=powerService.selects(strs);
            session.setAttribute("showpowers", powers);
             list=new ArrayList<String>();
            for (Power power:powers
            ) {
                list.add(power.getName());
            }
        }

        session.setAttribute("checkpowers", list);

        return new AjaxResult<>(user);
    }

    @GetMapping("/SignOut")
    public String signOut(HttpServletRequest request) {
        HttpSession session=request.getSession(true);
        session.invalidate();
        return "login";
    }
    @GetMapping("/welcome")
    public String welcome() {
        return "welcome";
    }

}
